package sword.chapter7Queue;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 最近请求次数
 *
 * @author K
 * @date 2021-12-05 17:09
 */
public class S42RecentCounter {
    private Queue<Integer> times;
    private int windowSize;

    S42RecentCounter() {
        times = new LinkedList<>();
        windowSize = 3000;
    }

    public int ping(int t) {
        times.offer(t);
        while (times.peek() + windowSize < t) {
            //截止时间小于当前时间，取出最开始的访问时间
            times.poll();
        }
        return times.size();
    }

    public static void main(String[] args) {
        S42RecentCounter s42RecentCounter = new S42RecentCounter();
        int ping = s42RecentCounter.ping(0);
        int ping2 = s42RecentCounter.ping(2000);
        int ping3 = s42RecentCounter.ping(3000);
        int ping4 = s42RecentCounter.ping(3001);
        int ping5 = s42RecentCounter.ping(4000);
        System.out.println();
    }
}

